// 引入 用来发送请求的方法，路径要补全
import {request} from "../../request/index.js";
var util = require('../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showModalStatus: false,
    commonHolder: '我要留言...',
    commentInfo: '',
    //当前页签
    currentTab: 0,
    // 当前用户
    userId:0,
    // 帖子详情
    topic:null,
    // 帖子ID
    topicId: 0,
    // 帖子图片
    topicImgList:[],
    // 已关注图标显示
    attentionState:false,
    // 用户与帖子最初的关注状态
    startAttentionState:null,
    // 评论列表
    commentList:[],
    // 评论数量
    commentCount:0,
    // 举报表单框
    showInformModal:false,
    // 评论表单框
    showCommentModal:false,
    // 点赞数据
    supportList: [],
    currUserSupport: false,
    // 键盘高度
    keyboardHeight: 0,
    // 是否为苹果手机
    isIOS: false,
    // 输入的评论内容
    message: '',
    // 查询评论每页大小
    limit: 10,
    // 查询评论当前页
    currentPage: 1,
  
    // 要回复的评论
    replyComm: null
  },


  // 点击评论或赞的事件
  changeTabHandle(e){
    let index = e.currentTarget.dataset.index;
    this.setData({
      currentTab: index
    })
  },

// 获取帖子详情
  getTopicDetail(id){
    request({url:util.BASE_URL + "topic/topicDetail/" + id})
    .then(result => {
      this.setData({
        topic:result.data,
        topicImgList:result.data.topicImgList,
        commentCount: result.data.commentCount
      })
    });
  },
// 退出页面时，浏览量 +1
  updateClickCount:function(){
    let id = this.data.topic.id;
    request({url:util.BASE_URL + "topic/updateClickCount/" + id})
    .then();
  },


// 删除自己的评论
  handleDelComment:function(e){
    let that = this;
    let commentId = this.data.replyComm.id;
    this.hideModal();
    wx.showModal({
      title:'删除评论',
      content: "删除这条评论吗？",
      confirmText:'删除',
      success:function(res){
        if(res.confirm){
          // 评论的帖子
          let topicId = that.data.topic.id;
          wx.request({
            url: util.BASE_URL +  'topic/delComment',
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            }, 
            data:{
              topicId,
              commentId
            },
            success:function(res){
              if(res.data.success == true){
                wx.showToast({
                  title: '已删除',
                  icon: 'none',
                  duration:1000
                })
                // 重新加载本帖子页面
                that.queryCommentForCommodity(topicId);
              } else{
                wx.showToast({
                  title: '删除失败',
                  icon: 'none',
                  duration:2000
                })
              }
            },
            fail:function(err){
              wx.showToast({
                title: '网络错误',
                icon: 'none',
                duration: 2000
              })
            }
          })
        } else{
        }
      }
    })
  },

  initSupport(id){
    let that = this;
    wx.request({
      url: `${util.BASE_URL}commentSupport/all/${id}`,
      method: 'GET',
      success({data}){
        that.dealWithSupport(data.data || []);
      }
    })
  },

  // 点赞
  handleSupport(){
    let userId = util.verifyHasLogin();
    if(userId){
      let {topicId, currUserSupport} = this.data;
      let url = 'commentSupport/add';
      let method = "POST";
      let that = this;
      // 点赞则取消点赞
      if(currUserSupport){
        url = 'commentSupport/delete';
        method = "DELETE";
      }
      wx.request({
        url: `${util.BASE_URL}${url}`,
        method: method,
        data: {
          topicId,
          userId
        },
        success({data}){
          that.dealWithSupport(data.data || []);
        }
      })
    }
  },

  dealWithSupport(list){
    let userId = util.verifyHasLogin();
    let currUserSupport = false;  
    list.forEach((item, idx) => {
      if(userId == item.userId){
        currUserSupport = true;
      }
    });
    this.setData({
      supportList: list,
      currUserSupport
    });
  },

  // 初始化是绑定键盘事件
  initKeyboardHeight: function(){
    const that = this;
    wx.onKeyboardHeightChange(res => {
        let keyboardHeight = res.height;
        console.log("键盘高度为", keyboardHeight);
        that.setData({showComtBox: keyboardHeight > 0});
    })
  },

   // 查询评论信息
   queryCommentForCommodity(id){
    let that = this;
    let {limit, currentPage, commentList} = this.data;
    
    wx.request({
      url: `${util.BASE_URL}topic/commentList`,
      method: 'GET',
      data: {
        limit,
        page: currentPage,
        topicId: id
      },
      success({data}){
         let {records} = data.data;
         console.log("查询评论信息", records);
         if(records && records.length > 0){
           commentList = records;
           that.setData({commentList});
         }
      }
    })
  },

  
  // 点击回复评论
  replyCommentHandle(e){
    console.log('回复评论信息', e);
    const currentUserId = wx.getStorageSync('userInfo').id;
    let replyComm = e.currentTarget.dataset.value;
    if(-1 == replyComm.state){
      return;
    }
    this.setData({replyComm});
    // 不能给自己回复
    if(currentUserId == replyComm.userId){
      this.setData({
        commentInfo: replyComm.context
      })
      this.showModal();
      return;
    }
    this.commentInputTap();
  },

  // 弹出评论输入框输入数据事件
  commentTextAreaInputHandle(event){
    let {value} = event.detail;
    this.setData({message: value.trim()});
  },

  // 点击发送按钮事件
  sendCommentHandle(){
    let that = this;
    let {message, topicId, replyComm} = this.data;
    let userId = wx.getStorageSync('userInfo').id;
    let {nickName, avatarUrl} = wx.getStorageSync('userInfo');
    
    let data = {
      topicId: topicId,
      avatar: avatarUrl,
      uname: nickName,
      userId: userId,
      context: message,
      replyId: 0
    };
    if(replyComm){
      data['replyId'] = replyComm.commId;
      data['replyUid'] = replyComm.uid;
      data['replyUname'] = replyComm.uname;
    }
    wx.request({
      url: `${util.BASE_URL}topic/addComment`,
      method: 'POST',
      data,
      success(res){
        console.log("保存留言结果", res);
        if(res.data.success){
          util.success();
          that.setData({currentPage: 1, commentList: []});
          that.queryCommentForCommodity(topicId);
        }
      },
      fail(){},
      complete(){
        that.setData({replyComm: null});
      },
    })
  },

  // 点击评论框时，是隐藏的评论输入框获取焦点并显示
  commentInputTap: function(e){
    // 如果是点击的发送评论则情况回复数据
    if(e){
      this.setData({replyComm: null});
    }
    let uId = util.verifyHasLogin();
    if(!uId){
      return;
    }
    this.setData({showComtBox: true});
  },

  // 评论信息输入框获取焦点事件
  ctFocus: function(e){
    let keyboardHeight = e.detail.height;
    console.log("文本框键盘高度", keyboardHeight);
    this.setData({ keyboardHeight})
  },

  // 点击显示更多回复事件
  showMoreReplyHandle(e){
    let {index} = e.currentTarget.dataset;
    let {commentList} = this.data;
    commentList[index].show = true;
    let chidren = commentList[index].children;
    let temp = [];
    chidren.forEach(function(item, idx){
       item.show = true;
       temp.push(item);
    });
    commentList[index].children = temp;
    this.setData({commentList});
  },


  showModal: function() {
    // 显示遮罩层
    var animation = wx.createAnimation({
     duration: 200,
     timingFunction: "linear",
     delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
     animationData: animation.export(),
     showModalStatus: true
    })
    setTimeout(function() {
     animation.translateY(0).step()
     this.setData({
     animationData: animation.export()
     })
    }.bind(this), 200)
  },
  hideModal: function() {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
     duration: 200,
     timingFunction: "linear",
     delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
     animationData: animation.export(),
    })
    setTimeout(function() {
     animation.translateY(0).step()
     this.setData({
     animationData: animation.export(),
     showModalStatus: false
     })
    }.bind(this), 200)
  },




  // 点击复制按钮
  copyHandle(){
    let {commentInfo} = this.data;
    let that = this;
    wx.setClipboardData({
      data: commentInfo,
      success(res){
        that.hideModal();
        that.setData({commentInfo: ''});
      }
    })
  },





  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let id = options.id;
    this.setData({
      topicId: id
    });
    // 获取帖子详情
    this.getTopicDetail(id);
    this.initSupport(id);
    this.queryCommentForCommodity(id);
    // 当前用户Id
    let userId = wx.getStorageSync('userInfo').id;
    if(userId != undefined){
      this.setData({
        userId
      });
    }

    this.initKeyboardHeight();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.data.topic != null){
      let id = this.data.topic.id;
      // 获取帖子详情
      this.getTopicDetail(id);
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 当前用户
    let userId = wx.getStorageSync('userInfo').id;
    // 商品发布者
    let pubUserId = this.data.topic.user.id;
    // 不是自己发布的，加浏览量
    if(userId != pubUserId){
      // 关闭页面时，浏览量 +1
      this.updateClickCount();
    }
    if(userId != undefined){
      // 关注、取消关注
      // 关注状态没变，不进行任何操作
      if(this.data.startAttentionState == this.data.attentionState){
        return;
      } else{
        let attentionState = this.data.attentionState;
        let topicId = this.data.topic.id;
        if(attentionState){
          // 关注
          this.addAttention(topicId,userId);
        } else{
          // 取消关注
          this.deleteAttention(topicId,userId);
        }
      }
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})